package core;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import application.Application;
import application.Core;
/**
 * This class read from File and write to PipedOutputStream.
 * @author Josef Vopalecky
 */

public class PipedInputStreamFileReader extends Application{

	private String fileName;
	private Core core;
	private int id;
	
	/**
	 * Constructor. 
	 * @param name of file
	 * @param core reference to the core
	 */
	public PipedInputStreamFileReader(String name, Core core){
		fileName = name;
		this.core = core;
		setPriority(Thread.MIN_PRIORITY);
	}
	
	/**
	 * Set process ID.
	 * @param id Process ID.
	 */
	public void setID(int id){
		this.id = id;
	}
	
	/**
	 * Reading and writing.
	 */
	@Override
	public void code() {
		try {
			BufferedReader bfr = new BufferedReader(new FileReader(fileName));
			try {
				String str = bfr.readLine();
				while(str != null){
					core.write(id, str);
					str = bfr.readLine();
					try {// need sleep, without sleep lost data
						Thread.sleep(70);
					} catch (InterruptedException e) {
						core.getGui().writeConsole("Thread can't sleep.");
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				core.getGui().writeConsole("IOException");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			core.getGui().writeConsole("FileNotFoundException");
		}
		core.closeOut(id);	
		core.cleanLastProccess();
	}

}
